<?php

namespace app\api\controller\shop;

use app\admin\model\RefundReason;
use app\admin\model\shop\Category;
use app\api\model\Pay;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;
use think\Log;

/**
 * 团购订单接口
 */
class Shoporder extends Api
{
    protected $noNeedRight = ['*'];

    protected $noNeedLogin = ['notify'];

    //订单列表
    public function lists()
    {
        $order_status = input('order_status','all');

        $model = new \app\api\model\shop\ShopOrder();

        $condition = [
            'so.user_id'=>$this->auth->id
        ];

        switch ($order_status) {
            case "waitpay"://待付款
                $condition['so.order_status'] = 0;
                break;
            case "waituse"://待使用
                $condition['so.order_status'] = 2;
                break;
            case "complete"://已完成
                $condition['so.order_status'] = 3;
                break;
            case "refund"://退款
                $condition['so.order_status'] = 4;
                break;
        }

        $res = $model->lists($condition);

        $this->success('',$res);
    }

    //订单详情
    public function detail()
    {
        $params = input();
        try {
            $model = new \app\api\model\shop\ShopOrder();
            $params['user_id'] = $this->auth->id;
            $res = $model->userdetail($params);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('',$res);

    }

    //线下支付测试
    public function offlinepay()
    {
        $order_no = input('order_no','');

        try {
            $model = new \app\api\model\shop\ShopOrder();

            $res = $model->offlinepay($order_no,$this->auth->id);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('',$res);
    }

    //支付
    public function pay()
    {
        $order_no = $this->request->post('order_no');
        $paytype = $this->request->post('paytype');
        $method = $this->request->post('method');
        $appid = $this->request->post('appid'); //为APP的应用id
        $returnurl = $this->request->post('returnurl', '', 'trim');
        $openid = '';

        //非H5 支付,非余额
        if (in_array($method, ['miniapp', 'mp']) && $paytype == 'wxpay') {
            $user = User::get($this->auth->id);

            $openid = $user->wechat_open_id;
        }

        $orderInfo = \app\api\model\shop\ShopOrder::get(['order_no'=>$order_no]);
        if (!$orderInfo) {
            $this->error("未找到指定的订单");
        }
        if ($orderInfo['pay_status']) {
            $this->error("订单已经支付，请勿重复支付");
        }
        //订单过期
        if (!$orderInfo['pay_status'] && time() > $orderInfo['closetime']) {
            // 启动事务
            Db::startTrans();
            try {
                $orderInfo->save(['order_status' => -1,'order_status_name'=>'已关闭']);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
            $this->error("订单已失效");
        }
        $response = null;
        try {
            //$request = \think\Request::instance();
            //$notice_url = $request->root(true) . '/api/shop/shoporder/notify';
            //$response = \app\api\model\shop\ShopOrder::pay($order_no, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
            //$pay_model = new Pay();
            //$response = $pay_model->unipay($orderInfo['order_no'],$orderInfo['goods_name'],$paytype,$orderInfo['order_price'],$notice_url);
            //$response = $pay_model->pay($orderInfo['order_no'],$orderInfo['goods_name'],$orderInfo['order_price'],$openid,$paytype,$notice_url,$orderInfo['shop_id']);
            $shop_info = \app\shopapi\model\Shop::get($orderInfo['shop_id']);
            $ip = '';
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } else {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
            $request = \think\Request::instance();

            $back_url = $request->root(true) . '/api/shop/shoporder/notify';
            $pay_model = new \app\shopapi\model\lakala\Pay();

            $order_price = intval($orderInfo['order_price']*100);

            $amount = intval((100-$shop_info['commission_rate'])/100*$orderInfo['order_price']*100);

            $split_list = [
                [
                    'member_no'=>$shop_info['member_no'],
                    'amount'=>$amount
                ]
            ];

            $data = [
                'shop_id'=>$orderInfo['shop_id'],
                'amount'=>$order_price,
                'seller_member_no'=>$shop_info['member_no'],
//                'user_id'=>$shop_info['user_id'],
                'user_id'=>$this->auth->id,
                'terminal_ip'=>$ip,
                'back_url'=>$back_url,
                'order_name'=>$orderInfo['goods_name'],
                'split_mode'=>1,
                'split_rule_data'=>$split_list
            ];

            $response = $pay_model->orderConsume($data);
            \app\api\model\shop\ShopOrder::update(['lakala_order_no'=>$response['order_no']],['order_no'=>$order_no]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("请求成功", $response);
    }

    //退款
    public function refund()
    {
        $params = input();
        try {
            $model = new \app\api\model\shop\ShopOrder();
            $params['user_id'] = $this->auth->id;
            $res = $model->refund($params);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('退款成功',$res);
    }

    //退款原因
    public function reason()
    {
        $type = input('type',1);
        $list = RefundReason::where(['type'=>$type])->order('weigh desc')->field('title')->select();

        $this->success('',$list);
    }

    /**
     * @ DateTime 2021-06-01
     * @ 支付回调
     * @return void
     */
    public function notify()
    {
        $event = input('event');
        $event_type = input('event_type');
        Log::error('团购:'.$event);
        $event = _json_decode($event,true);
        if ($event_type=='order.consume.pay'){
            $order_no = $event['order_no'];
            Log::error('团购订单号:'.$order_no);
            $out_order_no = $event['out_order_no'];
            $pay_status = $event['pay_status'];
            $pay_time = $event['pay_time'];
            $status = $event['status'];
            $third_party_payment = $event['third_party_payment'];
            $pay_seq_no = $event['pay_seq_no'];
            $split_seq_no = isset($event['split_seq_no'])? $event['split_seq_no']:'';
            $pay_model = new \app\api\model\shop\ShopOrder();
            if ($status=='OK') {
                if ($pay_status == 1004) {
                    $pay_amount = $event['pay_amount']/100;
                    $response = $pay_model->orderPay($order_no, $pay_amount, $third_party_payment,$pay_time,$pay_seq_no,$split_seq_no);
                    $this->success("请求成功", $response);
                }
            }
        } elseif ($event_type=='order.channel.fee'){
            $order_no = $event['order_no'];
            $request_no = $event['request_no'];
            $request_status = $event['request_status'];
            $channel_fee = $event['channel_fee']/100;
            $trade_amount = $event['trade_amount'];

            \app\shopapi\model\ShopOrder::update(['channel_fee'=>$channel_fee],['lakala_order_no'=>$order_no]);
        }

        $this->error("请求失败");
    }

    /**
     * @ DateTime 2021-06-01
     * @ 支付回调
     * @return void
     */
    public function oldnotify()
    {
        $data = input();
        Log::error('商户团购回调'.json_encode($data,320));
        try {
            $order_no = input('order_no','');
            $trans_status = input('trans_status');//0订单 1成功 2撤消 3退款
            $trans_oktime =input('trans_oktime','');//支付完成时间
            $total_fee = input('total_fee',0);//付款金额
            $trans_type = input('trans_type','');//支付类型 wxpay alipay unionpay
            $transaction_id = input('transaction_id','');
            //$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            if ($trans_status==1){
                $pay_model = new \app\api\model\shop\ShopOrder();
                $response = $pay_model->orderPay($order_no, $total_fee, $trans_type,$trans_oktime,$transaction_id);
                $this->success("请求成功", $response);
                //\app\api\model\shop\ShopOrder::orderPay($order_no, $total_fee, $trans_type,$trans_oktime,$merchant_no);
            }
            $this->error("未付款");
        } catch (\Exception $e) {
            \think\Log::write($e->getMessage(), 'epay');
        }
        $this->error("回调失败");

    }


    //分账
    public function fenzhang()
    {
        //分账
        $pay_model = new \app\shopapi\model\lakala\Pay();
        //$split_amount = $order_info->pay_price-$order_info->channel_fee;
        $out_request_no = date("YmdHis") . sprintf("%08d", 12) . mt_rand(1000, 9999);
        $refund_res = $pay_model->orderComplete('7261626499149873152','7259491353764315136',$out_request_no,'0.01');
        dump($refund_res);die;
        if ($refund_res['code']==0){
            throw new \Exception($refund_res['msg']);
        }
    }
}